var express = require("express");
var router = express.Router();
var { cypModel } = require("../model/cyp");
var { mzhModel } = require("../model/mzh");
//接入支付宝沙箱配置
const alipaySdk = require("./alipay");
const AlipayFormData = require("alipay-sdk/lib/form").default;
router.use(express.urlencoded({ extended: true }));
/* GET home page. */
router.get("/index", async (req, res) => {
  let data = await cypModel.find();
  res.send({ data });
});
//支付接口
router.post("/payment", function (req, res, next) {
  let orderid = req.body.orderid;
  const formData = new AlipayFormData();
  console.log(orderid);
  //调用get方法
  formData.setMethod("get");
  //支付成功或者失败打开的页面
  formData.addField("returnUrl", "http://bilibili.com");

  formData.addField("bizContent", {
    outTradeNo: orderid,
    productCode: "FAST_INSTANT_TRADE_PAY",
    totalAmount: "0.01",
    subject: "测试",
  });
  const result = alipaySdk
    .exec("alipay.trade.page.pay", {}, { formData: formData })
    .catch((error) => console.error("报错信息:", error));
  result.then((resp) => {
    res.send({
      success: "true",
      code: 200,
      result: resp,
    });
  });
});
//将前端的围栏顶点存入数据库
router.post("/add", async (req, res) => {
  //将拿到的数据放到mzhModel中的fance字段中
  let data = await mzhModel.updateOne(
    { username: "admin" },
    { fence: req.body.markers }
  );
  res.send({
    code: 200
  })
});
//将围栏的值清空
router.post("/clear", async (req, res) => {
  let data = await mzhModel.updateOne(
    { username: "admin" },
    { fence: [], polygons: [], polygonstwo: [] },
  );
  res.send({
    code: 200
  })
});
// 获取最外层围栏顶点
router.get('/', async (req, res) => {
  let data = await mzhModel.find({ username: 'admin' })
  res.send({
    code: 200,
    fence: data[0].fence,
    polygons:data[0].polygons,
    polygonstwo:data[0].polygonstwo
  })
})
// 获取警告区围栏顶点
router.get('/one', async (req, res) => {
  let data = await mzhModel.find({ username: 'admin' })
  res.send({
    code:200,
    polygons:data[0].polygons,
  })
})
// 获取安全区围栏顶点
router.get('/two', async (req, res) => {
  let data = await mzhModel.find({ username: 'admin' })
  res.send({
    code:200,
    polygonstwo:data[0].polygonstwo,
  })
})
// 添加警告区围栏的顶点
router.post("/addone", async (req, res) => {
  let data = await mzhModel.updateOne(
    { username: "admin" },
    { polygons: req.body.markers }
  )
  res.send({
    data,
    code: 200,
  });
});
//添加安全区围栏的顶点
router.post("/addtwo", async (req, res) => {
  let data = await mzhModel.updateOne(
    { username: "admin" },
    { polygonstwo: req.body.markers }
  )
  res.send({
    data,
    code: 200,
  });
});
module.exports = router;
